package cn.springsoter.core.mp.config;

import java.util.Date;
import java.util.Objects;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import cn.springsoter.core.tool.constant.SpringSoterConstant;
import cn.springsoter.core.tool.utils.ThreadLocalUtil;

/**
 * 主动填充entity里标注了@TableField(fill = FieldFill.INSERT_UPDATE)的字段，不需要手动set值
 * 
 * @author kevin
 *
 */
@Component
public class MetaObjectHandlerConfig implements MetaObjectHandler {
	
	static final String CREATED_TIME = "createdTime";
	static final String UPDATED_TIME = "updatedTime";
	static final String IS_DELETED = "isDeleted";
	static final String CREATE_BY = "createdBy";
	static final String UPDATE_BY = "updatedBy";
	
	@Override
	public void insertFill(MetaObject metaObject) {
		Date date = new Date();
		try {
			if(Objects.isNull(metaObject.getValue(CREATED_TIME))) {
				setFieldValByName(CREATED_TIME, date, metaObject);
			}
		} catch (Exception e) {}
        try {
        	if(Objects.isNull(metaObject.getValue(IS_DELETED))) {
				setFieldValByName(IS_DELETED, SpringSoterConstant.ZERO, metaObject);
			}
		} catch (Exception e) {}
        try {
        	if(Objects.isNull(metaObject.getValue(CREATE_BY))) {
        		Long userId = (Long)ThreadLocalUtil.get(SpringSoterConstant.DEFAULT_THREADLOCAL_KEY_USERID);
        		setFieldValByName(CREATE_BY, userId, metaObject);
			}
		} catch (Exception e) {}
        
        updateFill(metaObject);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		Date date = new Date();
		try {
			if(Objects.isNull(metaObject.getValue(UPDATED_TIME))) {
				setFieldValByName(UPDATED_TIME, date, metaObject);
			}
		} catch (Exception e) {}
		try {
			if(Objects.isNull(metaObject.getValue(UPDATE_BY))) {
				Long userId = (Long)ThreadLocalUtil.get(SpringSoterConstant.DEFAULT_THREADLOCAL_KEY_USERID);
				setFieldValByName(UPDATE_BY, userId, metaObject);
			}
		} catch (Exception e) {}
	}
}
